<?php
/**
 * Created by: zhaoyi (834574377@qq.com)
 * Time: 2023/1/9 17:06
 * Blog: https://www.yuque.com/huangzhenlian
 */

declare(strict_types=1);

namespace App\Application\Api\Task;

use App\Annotation\Api;
use App\Application\Admin\Model\Order;
use App\Exception\ErrorException;
use Hyperf\AsyncQueue\Annotation\AsyncQueueMessage;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;

#[Controller("/api/OrderfzTask")]
#[Crontab(rule: "*\/5 * * * * *", name: "订单分账", callback: "orderfz", memo: "订单分账定时更新", enable: "isorderfz")]
class OrderfzTask
{
    //订单状态0未开始，1进行中，2已结束，3已退款，4已取消，5已分账，6待付款
    //订单分账定时更新
    //https://zly.qile168.net/api/OrderfzTask/orderfz
    #[Api]
    #[GetMapping("orderfz")]
    public function orderfz()
    {
        $where = [];
        $where[] = ['end_time', '<', time()];
        $where[] = ['status', '=', 2];
        $order = Order::where($where)->select('*')
            ->first() ?: [];
        if (!empty($order)) {
            $res = Order::where('order_id', '=', $order->order_id)->update([
                'status' => 5,
                'updated_at' => date('Y-m-d H:i:s', time())
            ]);
            if (!empty($res)) {
                return true;
            } else {
                return false;
            }
        }else{
            return false;
        }

//        Db::beginTransaction();
//        try {
//            //开始分账
//
//            //结束分账
//            //修改订单状态
//
//            Db::commit();
//        } catch (\Throwable $ex) {
//            Db::rollBack();
//        }
    }

    public function isorderfz(): bool
    {
        $where = [];
        $where[] = ['end_time', '<', time()];
        $where[] = ['status', '=', 2];
//是否存在已结束带分账订单
        $order = Order::where($where)->select('*')
            ->first() ?: [];
        if (!empty($order)) {
            return true;
        } else {
            return false;
        }
    }
}
